import 'package:flutter/material.dart';
import '../../models/post_model.dart';
import '../../services/api_service.dart';
import '../../utils/logger.dart';
import '../../utils/cached_image_widget.dart';
import 'package:base_flutter/src/network/network_exception.dart';
import 'video_player_page.dart';

/// 视频合集页面
/// 显示视频合集的详细信息，包括封面、描述、视频列表等
class VideoCollectionPage extends StatefulWidget {
  final PostModel post;

  const VideoCollectionPage({
    super.key,
    required this.post,
  });

  @override
  State<VideoCollectionPage> createState() => _VideoCollectionPageState();
}

class _VideoCollectionPageState extends State<VideoCollectionPage> {
  VideoCollectionModel? _collection;
  List<VideoModel> _videos = [];
  bool _isLoading = true;
  String? _error;

  @override
  void initState() {
    super.initState();
    _loadVideoCollection();
  }

  /// 加载视频合集详情
  Future<void> _loadVideoCollection() async {
    try {
      setState(() {
        _isLoading = true;
        _error = null;
      });

      // 并行加载合集信息和视频列表
      final futures = await Future.wait([
        ApiService().getVideoCollectionDetail(widget.post.id),
        // 这里需要先获取合集ID，暂时使用模拟数据
        Future.delayed(const Duration(seconds: 1), () => _getMockVideos()),
      ]);

      final collection = futures[0] as VideoCollectionModel;
      final videos = futures[1] as List<VideoModel>;

      setState(() {
        _collection = collection;
        _videos = videos;
        _isLoading = false;
      });

      Logger.d('VIDEO_COLLECTION', '视频合集加载成功');
    } catch (e) {
      Logger.e('VIDEO_COLLECTION', '视频合集加载失败: $e');
      setState(() {
        _error = e is NetworkException ? e.message : '加载失败';
        _isLoading = false;
      });
    }
  }

  /// 获取模拟视频数据
  List<VideoModel> _getMockVideos() {
    return [
      VideoModel(
        id: '1',
        collectionId: '1',
        title: '产品增长基础理论',
        url: 'https://example.com/video1.mp4',
        coverUrl: '',
        durationSec: 1200, // 20分钟
        orderNo: 0,
        createdAt: DateTime.now().subtract(const Duration(days: 1)),
      ),
      VideoModel(
        id: '2',
        collectionId: '1',
        title: '用户获取策略详解',
        url: 'https://example.com/video2.mp4',
        coverUrl: '',
        durationSec: 1800, // 30分钟
        orderNo: 1,
        createdAt: DateTime.now().subtract(const Duration(days: 2)),
      ),
      VideoModel(
        id: '3',
        collectionId: '1',
        title: '用户留存优化技巧',
        url: 'https://example.com/video3.mp4',
        coverUrl: '',
        durationSec: 1500, // 25分钟
        orderNo: 2,
        createdAt: DateTime.now().subtract(const Duration(days: 3)),
      ),
      VideoModel(
        id: '4',
        collectionId: '1',
        title: '变现模式设计',
        url: 'https://example.com/video4.mp4',
        coverUrl: '',
        durationSec: 2100, // 35分钟
        orderNo: 3,
        createdAt: DateTime.now().subtract(const Duration(days: 4)),
      ),
    ];
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('视频合集'),
        backgroundColor: Colors.white,
        foregroundColor: Colors.black,
        elevation: 0,
        actions: [
          IconButton(
            icon: const Icon(Icons.share),
            onPressed: _handleShare,
          ),
          IconButton(
            icon: const Icon(Icons.more_vert),
            onPressed: _showMoreOptions,
          ),
        ],
      ),
      body: _buildBody(),
    );
  }

  Widget _buildBody() {
    if (_isLoading) {
      return const Center(
        child: CircularProgressIndicator(),
      );
    }

    if (_error != null) {
      return Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(
              Icons.error_outline,
              size: 64,
              color: Colors.grey[400],
            ),
            const SizedBox(height: 16),
            Text(
              _error!,
              style: TextStyle(
                fontSize: 16,
                color: Colors.grey[600],
              ),
            ),
            const SizedBox(height: 16),
            ElevatedButton(
              onPressed: _loadVideoCollection,
              child: const Text('重试'),
            ),
          ],
        ),
      );
    }

    return SingleChildScrollView(
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 合集封面和基本信息
          _buildCollectionHeader(),
          
          // 作者信息
          _buildAuthorInfo(),
          
          // 合集描述
          if (_collection?.description != null && _collection!.description!.isNotEmpty)
            _buildDescription(),
          
          // 互动区域
          _buildInteractionArea(),
          
          // 视频列表
          _buildVideoList(),
        ],
      ),
    );
  }

  /// 构建合集头部
  Widget _buildCollectionHeader() {
    return Container(
      width: double.infinity,
      height: 250,
      decoration: BoxDecoration(
        color: Colors.grey[800],
        image: widget.post.coverUrl != null && widget.post.coverUrl!.isNotEmpty
            ? DecorationImage(
                image: NetworkImage(widget.post.coverUrl!),
                fit: BoxFit.cover,
              )
            : null,
      ),
      child: Container(
        decoration: BoxDecoration(
          gradient: LinearGradient(
            begin: Alignment.topCenter,
            end: Alignment.bottomCenter,
            colors: [
              Colors.transparent,
              Colors.black.withOpacity(0.7),
            ],
          ),
        ),
        child: Stack(
          children: [
            Positioned(
              bottom: 20,
              left: 20,
              right: 20,
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    widget.post.content,
                    style: const TextStyle(
                      fontSize: 20,
                      fontWeight: FontWeight.bold,
                      color: Colors.white,
                    ),
                    maxLines: 2,
                    overflow: TextOverflow.ellipsis,
                  ),
                  const SizedBox(height: 8),
                  Row(
                    children: [
                      Icon(
                        Icons.play_circle_outline,
                        color: Colors.white,
                        size: 16,
                      ),
                      const SizedBox(width: 4),
                      Text(
                        '${_videos.length}个视频',
                        style: const TextStyle(
                          color: Colors.white,
                          fontSize: 14,
                        ),
                      ),
                      const SizedBox(width: 16),
                      Icon(
                        Icons.access_time,
                        color: Colors.white,
                        size: 16,
                      ),
                      const SizedBox(width: 4),
                      Text(
                        _getTotalDuration(),
                        style: const TextStyle(
                          color: Colors.white,
                          fontSize: 14,
                        ),
                      ),
                    ],
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  /// 构建作者信息
  Widget _buildAuthorInfo() {
    return Container(
      padding: const EdgeInsets.all(16),
      child: Row(
        children: [
          CircleAvatar(
            radius: 24,
            backgroundColor: Colors.grey[300],
            backgroundImage: widget.post.userAvatar != null && widget.post.userAvatar!.isNotEmpty
                ? NetworkImage(widget.post.userAvatar!)
                : null,
            child: widget.post.userAvatar == null || widget.post.userAvatar!.isEmpty
                ? const Icon(Icons.person, size: 28, color: Colors.grey)
                : null,
          ),
          const SizedBox(width: 12),
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  widget.post.username,
                  style: const TextStyle(
                    fontSize: 16,
                    fontWeight: FontWeight.bold,
                  ),
                ),
                const SizedBox(height: 4),
                Row(
                  children: [
                    Icon(
                      Icons.location_on,
                      size: 14,
                      color: Colors.grey[600],
                    ),
                    const SizedBox(width: 4),
                    Text(
                      widget.post.location ?? '',
                      style: TextStyle(
                        fontSize: 12,
                        color: Colors.grey[600],
                      ),
                    ),
                    const SizedBox(width: 12),
                    Text(
                      _getTimeAgo(widget.post.createdAt),
                      style: TextStyle(
                        fontSize: 12,
                        color: Colors.grey[600],
                      ),
                    ),
                  ],
                ),
              ],
            ),
          ),
          ElevatedButton(
            onPressed: _handleFollow,
            child: const Text('关注'),
          ),
        ],
      ),
    );
  }

  /// 构建描述
  Widget _buildDescription() {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 16),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          const Text(
            '合集介绍',
            style: TextStyle(
              fontSize: 16,
              fontWeight: FontWeight.bold,
            ),
          ),
          const SizedBox(height: 8),
          Text(
            _collection?.description ?? widget.post.summary ?? '',
            style: TextStyle(
              fontSize: 14,
              color: Colors.grey[700],
              height: 1.5,
            ),
          ),
          const SizedBox(height: 16),
        ],
      ),
    );
  }

  /// 构建互动区域
  Widget _buildInteractionArea() {
    return Container(
      margin: const EdgeInsets.symmetric(horizontal: 16),
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: Colors.grey[50],
        borderRadius: BorderRadius.circular(8),
        border: Border.all(color: Colors.grey[200]!),
      ),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
        children: [
          _buildInteractionButton(
            icon: widget.post.isLiked ? Icons.favorite : Icons.favorite_border,
            label: '${widget.post.likesCount}',
            color: widget.post.isLiked ? Colors.red : Colors.grey[600],
            onTap: _handleLike,
          ),
          _buildInteractionButton(
            icon: Icons.comment,
            label: '${widget.post.commentsCount}',
            color: Colors.grey[600],
            onTap: _handleComment,
          ),
          _buildInteractionButton(
            icon: Icons.share,
            label: '${widget.post.sharesCount}',
            color: Colors.grey[600],
            onTap: _handleShare,
          ),
          _buildInteractionButton(
            icon: Icons.visibility,
            label: '${widget.post.viewsCount}',
            color: Colors.grey[600],
            onTap: () {},
          ),
        ],
      ),
    );
  }

  /// 构建互动按钮
  Widget _buildInteractionButton({
    required IconData icon,
    required String label,
    required Color? color,
    required VoidCallback onTap,
  }) {
    return GestureDetector(
      onTap: onTap,
      child: Column(
        children: [
          Icon(
            icon,
            color: color,
            size: 24,
          ),
          const SizedBox(height: 4),
          Text(
            label,
            style: TextStyle(
              color: color,
              fontSize: 12,
            ),
          ),
        ],
      ),
    );
  }

  /// 构建视频列表
  Widget _buildVideoList() {
    return Container(
      padding: const EdgeInsets.all(16),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          const Text(
            '视频列表',
            style: TextStyle(
              fontSize: 18,
              fontWeight: FontWeight.bold,
            ),
          ),
          const SizedBox(height: 16),
          ListView.builder(
            shrinkWrap: true,
            physics: const NeverScrollableScrollPhysics(),
            itemCount: _videos.length,
            itemBuilder: (context, index) {
              final video = _videos[index];
              return _buildVideoItem(video, index);
            },
          ),
        ],
      ),
    );
  }

  /// 构建视频项
  Widget _buildVideoItem(VideoModel video, int index) {
    return Container(
      margin: const EdgeInsets.only(bottom: 12),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(8),
        border: Border.all(color: Colors.grey[200]!),
      ),
      child: InkWell(
        onTap: () => _playVideo(video),
        borderRadius: BorderRadius.circular(8),
        child: Padding(
          padding: const EdgeInsets.all(12),
          child: Row(
            children: [
              // 视频封面
              Container(
                width: 120,
                height: 80,
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(6),
                  color: Colors.grey[200],
                ),
                child: Stack(
                  children: [
                    ClipRRect(
                      borderRadius: BorderRadius.circular(6),
                      child: CachedCoverWidget(
                        coverUrl: video.coverUrl,
                        width: 120,
                        height: 80,
                        showPlayButton: false,
                      ),
                    ),
                    // 播放按钮
                    Center(
                      child: Container(
                        padding: const EdgeInsets.all(8),
                        decoration: BoxDecoration(
                          color: Colors.black.withOpacity(0.6),
                          shape: BoxShape.circle,
                        ),
                        child: const Icon(
                          Icons.play_arrow,
                          color: Colors.white,
                          size: 20,
                        ),
                      ),
                    ),
                    // 时长
                    Positioned(
                      bottom: 4,
                      right: 4,
                      child: Container(
                        padding: const EdgeInsets.symmetric(horizontal: 4, vertical: 2),
                        decoration: BoxDecoration(
                          color: Colors.black.withOpacity(0.7),
                          borderRadius: BorderRadius.circular(4),
                        ),
                        child: Text(
                          video.formattedDuration,
                          style: const TextStyle(
                            color: Colors.white,
                            fontSize: 10,
                          ),
                        ),
                      ),
                    ),
                  ],
                ),
              ),
              const SizedBox(width: 12),
              // 视频信息
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      video.title,
                      style: const TextStyle(
                        fontSize: 14,
                        fontWeight: FontWeight.w500,
                      ),
                      maxLines: 2,
                      overflow: TextOverflow.ellipsis,
                    ),
                    const SizedBox(height: 4),
                    Text(
                      '第${index + 1}集',
                      style: TextStyle(
                        fontSize: 12,
                        color: Colors.grey[600],
                      ),
                    ),
                    const SizedBox(height: 4),
                    Row(
                      children: [
                        Icon(
                          Icons.access_time,
                          size: 12,
                          color: Colors.grey[600],
                        ),
                        const SizedBox(width: 4),
                        Text(
                          video.formattedDuration,
                          style: TextStyle(
                            fontSize: 12,
                            color: Colors.grey[600],
                          ),
                        ),
                      ],
                    ),
                  ],
                ),
              ),
              // 更多按钮
              IconButton(
                icon: const Icon(Icons.more_vert),
                onPressed: () => _showVideoOptions(video),
              ),
            ],
          ),
        ),
      ),
    );
  }

  /// 播放视频
  void _playVideo(VideoModel video) {
    Navigator.push(
      context,
      MaterialPageRoute(
        builder: (context) => VideoPlayerPage(
          post: widget.post,
          videoUrl: video.url,
          videoTitle: video.title,
        ),
      ),
    );
  }

  /// 显示视频选项
  void _showVideoOptions(VideoModel video) {
    showModalBottomSheet(
      context: context,
      builder: (context) => Container(
        padding: const EdgeInsets.all(16),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            ListTile(
              leading: const Icon(Icons.download),
              title: const Text('下载'),
              onTap: () {
                Navigator.pop(context);
                ScaffoldMessenger.of(context).showSnackBar(
                  const SnackBar(content: Text('下载功能开发中...')),
                );
              },
            ),
            ListTile(
              leading: const Icon(Icons.share),
              title: const Text('分享'),
              onTap: () {
                Navigator.pop(context);
                ScaffoldMessenger.of(context).showSnackBar(
                  const SnackBar(content: Text('分享功能开发中...')),
                );
              },
            ),
          ],
        ),
      ),
    );
  }

  /// 处理点赞
  void _handleLike() async {
    try {
      await ApiService().likePost(widget.post.id, !widget.post.isLiked);
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text(!widget.post.isLiked ? '已点赞' : '已取消点赞'),
        ),
      );
    } catch (e) {
      Logger.e('VIDEO_COLLECTION', '点赞失败: $e');
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text('操作失败: ${e is NetworkException ? e.message : '网络错误'}'),
          backgroundColor: Colors.red,
        ),
      );
    }
  }

  /// 处理评论
  void _handleComment() {
    // TODO: 实现评论功能
    ScaffoldMessenger.of(context).showSnackBar(
      const SnackBar(content: Text('评论功能开发中...')),
    );
  }

  /// 处理分享
  void _handleShare() async {
    try {
      await ApiService().sharePost(widget.post.id);
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('分享成功')),
      );
    } catch (e) {
      Logger.e('VIDEO_COLLECTION', '分享失败: $e');
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text('分享失败: ${e is NetworkException ? e.message : '网络错误'}'),
          backgroundColor: Colors.red,
        ),
      );
    }
  }

  /// 处理关注
  void _handleFollow() {
    // TODO: 实现关注功能
    ScaffoldMessenger.of(context).showSnackBar(
      const SnackBar(content: Text('关注功能开发中...')),
    );
  }

  /// 显示更多选项
  void _showMoreOptions() {
    showModalBottomSheet(
      context: context,
      builder: (context) => Container(
        padding: const EdgeInsets.all(16),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            ListTile(
              leading: const Icon(Icons.bookmark_border),
              title: const Text('收藏'),
              onTap: () {
                Navigator.pop(context);
                ScaffoldMessenger.of(context).showSnackBar(
                  const SnackBar(content: Text('收藏功能开发中...')),
                );
              },
            ),
            ListTile(
              leading: const Icon(Icons.report),
              title: const Text('举报'),
              onTap: () {
                Navigator.pop(context);
                ScaffoldMessenger.of(context).showSnackBar(
                  const SnackBar(content: Text('举报功能开发中...')),
                );
              },
            ),
          ],
        ),
      ),
    );
  }

  /// 获取总时长
  String _getTotalDuration() {
    final totalSeconds = _videos.fold<int>(0, (sum, video) => sum + (video.durationSec ?? 0));
    final hours = totalSeconds ~/ 3600;
    final minutes = (totalSeconds % 3600) ~/ 60;
    
    if (hours > 0) {
      return '${hours}小时${minutes}分钟';
    } else {
      return '${minutes}分钟';
    }
  }

  /// 获取时间差
  String _getTimeAgo(DateTime dateTime) {
    final now = DateTime.now();
    final difference = now.difference(dateTime);

    if (difference.inDays > 0) {
      return '${difference.inDays}天前';
    } else if (difference.inHours > 0) {
      return '${difference.inHours}小时前';
    } else if (difference.inMinutes > 0) {
      return '${difference.inMinutes}分钟前';
    } else {
      return '刚刚';
    }
  }
}
